import React, { useCallback, useEffect, useState } from "react";
import { Form, Button, Modal, Space, Badge, Menu } from "antd";
import { Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import SplitOrderModal from "./component/SplitOrderModal";
import ReleaseSortModal from "./component/ReleaseSortModal";
import DeliverOrderModal from "./component/DeliverOrderModal";
import OrderDetailModal from "./component/OrderDetailModal";
import SortConfigModal from "./component/SortConfigModal";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import { getSortingBoxList, getSortingBoxStatistics, getSortingDoneNum } from "../service";
import WarehouseSelect from "@/views/components/WarehouseSelect";
import { StatusText } from "@/pages/OrderModule/common/components/CommonText";
import { getLabelByValue, ORDER_OCCUPY_STATUS, ORDER_SORT_STATUS, ORDER_NUMBER } from "@/views/utils/constant";
import { hiprintTipsModal } from "@/utils/utils.jsx";
import { usePrintExpress } from "@/views/hooks/usePrintExpress";

const { Option } = Select;
//
const SortFrameList = () => {
	const [visible, setVisible] = useState(0);
	const [configVisible, setConfigVisible] = useState(0);
	const [detailVisible, setDetailVisible] = useState(false);
	const [statistics, setStatistics] = useState({});
	const [records, setRecords] = useState({});
	const [defaultValue, setDefaultValue] = useState(null);
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [outboundNoList, setOutboundNoList] = useState([]);
	const tableRequest = getSortingBoxList;
	const defaultColumns = [
		{
			name: "分拣墙",
			code: "wallName",
			search: {
				order: 3,
				content: () => <Input allowClear placeholder="分拣墙" />
			},
			width: 120
		},
		{
			name: "分拣框",
			code: "boxName",
			search: {
				code: "name",
				order: 2,
				content: () => <Input allowClear placeholder="分拣框" />
			},
			width: 120
		},
		{
			name: "出库单号",
			code: "outboundNo",
			render: (text, record) => (
				<span className="common-color2" onClick={() => orderDetail(text, record)}>
					{text}
				</span>
			),
			search: {
				order: 7,
				code: "outboundNoList",
				content: () => (
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						maxItem={500}
						modalProps={{
							title: "批量输入"
						}}
						placeholder="多个出库单号，以逗号隔开"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					/>
				)
			},
			width: 160
		},
		{
			name: "系统订单号",
			code: "systemNo",
			render: (text, record) => (
				<span className="common-color2" onClick={() => orderDetail(text, record)}>
					{text}
				</span>
			),
			search: {
				order: 7,
				code: "systemNoList",
				content: () => (
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						maxItem={500}
						modalProps={{
							title: "批量输入"
						}}
						placeholder="多个系统订单号，以逗号隔开"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					/>
				)
			},
			width: 160
		},
		// {
		// 	name: "订单占用状态",
		// 	code: "occupancyStatus",
		// 	search: {
		// 		order: 5,
		// 		content: () => <Select allowClear placeholder="是否占用" options={ORDER_OCCUPY_STATUS} />
		// 	},
		// 	render: text => <div style={{ color: text == 1 ? "rgba(240, 61, 41, 1)" : "" }}>{text == 1 ? "已占用" : "未占用"}</div>,
		// 	width: 120
		// },
		{
			name: "订单分拣状态",
			code: "sortingStatus",
			search: {
				order: 6,
				content: () => <Select allowClear placeholder="订单分拣状态" options={ORDER_SORT_STATUS} />
			},
			render: (_, record) => (
				<div>
					{record.sortingStatus == 0 && (
						<span className="flex">
							<StatusText type="error" text="" />
							<div style={{ color: "rgba(240, 61, 41, 1)" }}>未分拣</div>
						</span>
					)}
					{record.sortingStatus == 1 && (
						<span className="flex">
							<StatusText type="warning" text="" />
							<div style={{ color: "rgba(255, 144, 0, 1)" }}>部分分拣</div>
						</span>
					)}
					{record.sortingStatus == 2 && (
						<span className="flex">
							<StatusText type="success" text="" />
							<div>分拣完成</div>
						</span>
					)}
				</div>
			),
			width: 120
		},
		{
			name: "商品总数",
			code: "outboundCount",
			search: {
				order: 1,
				code: "warehouseId",
				formItemProps: {
					initialValue: defaultValue
				},
				content: () => {
					return (
						<WarehouseSelect
							placeholder={"所属仓库"}
							{...WarehouseSelectProps}
							defaultValued={getDefaultValued}
							value={selectedWarehouse}
							onChange={handleWarehouseChange}
						/>
					);
				}
			},
			width: 100
		},
		{
			name: "已分拣商品数",
			code: "sortedCount",
			search: {
				order: 180,
				span: 6,
				group: [
					{
						span: 9,
						code: "sortingFlag",
						content: () => <Select origin style={{ width: "100%" }} allowClear placeholder="已分拣数" options={ORDER_NUMBER} />
					},
					{
						code: "sortingNum",
						content: () => <Input origin allowClear placeholder="数量" />
					}
				]
			},
			width: 120
		}
	];

	const [columns, setColumns] = useState(defaultColumns);
	const commonHandleClick = (status, record) => {
		console.log("commonHandleClick", status);
		if (selectedRows.length || status == 2) {
			if (status == 1) {
				const list = selectedRows.filter(x => x.outboundNo);
				setOutboundNoList(list);
				if (list.length === 0) {
					Modal.info({ centered: true, content: "请选择有出库单号的数据" });
				} else {
					setVisible(status);
				}
			} else if (status == 2) {
				if (!hiprint.hiwebSocket.opened) {
					return hiprintTipsModal();
				}
				// const list = dataSource?.filter(x => x.sortingStatus == 2);
				// setOutboundNoList(list);
				if (outboundNoList.length === 0) {
					Modal.info({ centered: true, content: "请选择有分拣完成的数据" });
				} else {
					setVisible(status);
				}
			} else {
				setVisible(status);
			}
		} else {
			Modal.info({ centered: true, content: "请先选择数据" });
		}
	};
    //根据仓库id查询已分拣完成的出库单
	const getDataSoure = async (warehouseId) => {
		const response = await getSortingDoneNum({ warehouseId });
		console.log(response, 'response[===================')
		if (response.success) {
			setOutboundNoList(response.data);
		}
	}
	const orderDetail = (text, record) => {
		setRecords(record);
		setDetailVisible(true);
	};
	const handleWarehouseChange = value => {
		setSelectedWarehouse(value);
	};
	const tableKey = "SortFrameList23213";
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		query,
		form,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: true,
		hasQuickSearch: false,
		beforeQuerySearch: false,
		columnResize: true,
		resetSourceData: false,
		hasColsSetting: false
	});

	const { printExpress } = usePrintExpress({
		callback: data => {}
	});

	const CheckStockAndNoteProps = {
		visible,
		query,
		selectedKeys,
		fetchList,
		dataSource,
		outboundNoList,
		selectedRows,
		handlePrint(arr) {
			if (arr?.length) {
				printExpress(arr, 2);
			}
		},
		handleOk() {
			fetchList();
			handleStatistics({ warehouseId: form.getFieldValue("warehouseId") || query.warehouseId });
			setVisible(0);
		},
		handleCancel() {
			setVisible(0);
		}
	};
	const WarehouseSelectProps = {
		// isTitle: true,
		isDefault: true
	};
	const CheckOrderDetailProps = {
		detailVisible,
		query,
		records,
		handleOk() {},
		handleCancel() {
			setDetailVisible(false);
		}
	};

	const getDefaultValued = val => {
		setDefaultValue(val);
		fetchList({ warehouseId: val });
		handleStatistics({ warehouseId: val });
		getDataSoure(val);
		form.setFieldValue("warehouseId", val);
	};
	const handleStatistics = async val => {
		const { data, success } = await getSortingBoxStatistics(val);
		if (success) {
			setStatistics(data);
		}
	};

	//分拣框设置
	const SortConfigModalProps = {
		visible: configVisible,
		handleCancel() {
			setConfigVisible(false);
		}
	};

	useEffect(() => {
		if (query.warehouseId) {
			handleStatistics({ warehouseId: query.warehouseId });
            getDataSoure(query.warehouseId);
		}
	}, [dataSource]);

	const leftBtns = (
		<Space>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(1)}>
				拆分订单
			</Button>
			<Badge count={statistics.boxFullNum} overflowCount={999} style={{ zIndex: 9, marginRight: "4px" }}>
				<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(2)}>
					发货已配齐订单
				</Button>
			</Badge>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick(3)}>
				释放分拣框
			</Button>
		</Space>
	);

	const rightBtns = (
		<div style={{ display: "flex", alignItems: "center" }}>
			<div style={{ marginRight: 16 }}>分拣框数：{statistics.boxTotalNum}</div>
			<div style={{ marginRight: 16 }}>已占用：{statistics.boxOccupyNum}</div>
			<div style={{ marginRight: 16 }}>未占用：{statistics.boxFreeNum}</div>
			<Button style={{ marginRight: "8px" }} onClick={() => setConfigVisible(true)}>
				分拣框设置
			</Button>
		</div>
	);
	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={leftBtns} rightBtns={rightBtns} {...searchSimpleTableProps} />
			{visible == 1 && <SplitOrderModal {...CheckStockAndNoteProps} />}
			{visible == 2 && <DeliverOrderModal {...CheckStockAndNoteProps} />}
			{visible == 3 && <ReleaseSortModal {...CheckStockAndNoteProps} />}
			{detailVisible && <OrderDetailModal {...CheckOrderDetailProps} />}
			{!!configVisible && <SortConfigModal {...SortConfigModalProps} />}
		</>
	);
};

export default React.memo(SortFrameList, () => {
	return true;
});
